/* Author: Tyler Gordon

*/

// Twitter feed widget
// --------------------------------------------------
function getTweets(user,limit) {
  // Create a Script Tag
  var script=document.createElement('script');
  script.type='text/javascript';
  script.src= "https://api.twitter.com/1/statuses/user_timeline.json?screen_name="+user+
    "&count="+limit+
    "&callback=processTweets&_="+ new Date().getTime();
  // Add the Script to the Body element, which will in turn load the script and run it.
  $("body").append(script);
}

function wrapHash(s) {
  var hashRegex = /#.+?(\s|$)/gi;
  var matches = s.match(hashRegex);
  var tag = '<a href="http://twitter.com/search/?q={0}&src=hash" target="_blank">{1}</a>';
  if( matches==null ) {
    return s;
  }
  for( var i=0, len = matches.length; i<len; i++) {
    matches[i] = matches[i].replace(/^\s+|\s+$/g,'');
    var cleaned = matches[i].replace('#', '%23' );
    var to = tag.format(cleaned,matches[i]);
    s = s.replace(matches[i], to);
  }
  return s;
}

function wrapURL(s) {
  var urlRegex = /(f|ht)tps?:\/\/.+?(\s|$)/gi;
  var matches = s.match(urlRegex);
  if( matches==null ) {
    return s;
  }
  for( var i=0, len = matches.length; i<len; i++) {
    matches[i] = matches[i].replace(/^\s+|\s+$/g,'');
    var to = '<a href="' + matches[i] + '" target="_blank">' + matches[i]+ "</a>";
    s = s.replace(matches[i], to);
  }
  return s;
}

function processTweets(jsonData){
  var shtml = '';
  if(jsonData){
    // if there are results (it should be an array), loop through it with a jQuery function
    var wrapper = "<p class='tweet'><span class='author'><a href='http://twitter.com/{0}' target='_blank'>@{0}</a></span>: {1}</p>";
    $.each(jsonData, function(index,value){
      shtml += wrapper.format( value.user.screen_name, wrapHash(wrapURL(value.text)));
    });

    // Load the HTML in the #tweet_stream div
    $("#tweets").html( shtml );
  } else {
    $("#tweets").html( "Sorry. No tweets were available." );
  }
}

String.prototype.format = function() {
  var args = arguments;
  return this.replace(/{(\d+)}/g, function(match, number) { 
    return typeof args[number] != 'undefined'
      ? args[number]
      : match
    ;
  });
};

$(document).ready( function() {

});

